package com.shengruan.user.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shengruan.admin.jdbc.OrdersJdbc;
import com.shengruan.admin.vo.Orders;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.common.alipay.AlipayBase;
import com.shengruan.common.alipay.AlipayNotify;


public class UserOrdersNotifyUrlAction  extends BaseAction {

    Logger logger = LoggerFactory.getLogger(getClass());

    private OrdersJdbc ordersJdbc = (OrdersJdbc) this.getJdbc(OrdersJdbc.class);


    @Override
    public void execute() throws Exception {
        PropertiesConfiguration config = new PropertiesConfiguration("AlipayConfig.properties");
        String key = config.getString("key");
        //获取支付宝POST过来反馈信息
        Map params = new HashMap();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
            params.put(name, valueStr);
        }

        //判断responsetTxt是否为ture，生成的签名结果mysign与获得的签名结果sign是否一致
        //responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
        //mysign与sign不等，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
        String mysign = AlipayNotify.GetMysign(params, key);
        String responseTxt = AlipayNotify.Verify(request.getParameter("notify_id"));
        String sign = request.getParameter("sign");

        //写日志记录（若要调试，请取消下面两行注释）
        String sWord = "responseTxt=" + responseTxt + "\n notify_url_log:sign=" + sign + "&mysign=" + mysign + "\n notify params: " + AlipayBase.CreateLinkString(params);
        //AlipayBase.LogResult(sWord);
        logger.info(sWord);


        //获取支付宝的通知返回参数
        String trade_no = request.getParameter("trade_no");                //支付宝交易号
        String order_no = request.getParameter("out_trade_no");            //获取订单号
        String total_fee = request.getParameter("total_fee");            //获取总金额
        String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"), "UTF-8");//商品名称、订单名称
        String body = new String(request.getParameter("body").getBytes("ISO-8859-1"), "UTF-8");//商品描述、订单备注、描述
        String buyer_email = request.getParameter("buyer_email");        //买家支付宝账号
        String trade_status = request.getParameter("trade_status");        //交易状态
        int sOld_trade_status = 0;                //获取商户数据库中查询得到该笔交易当前的交易状态


        String verifyStatus = "";

        if (mysign.equals(sign) && responseTxt.equals("true")) {//验证成功

            Orders orders = this.ordersJdbc.getByOrderNumber(order_no);

            if(null != orders) {
                sOld_trade_status = orders.getStatus(); //获取商户数据库中查询得到该笔交易当前的交易状态
                //假设：
                //sOld_trade_status=0	表示订单未处理；
                //sOld_trade_status=1	表示交易成功（TRADE_FINISHED/TRADE_SUCCESS）

                if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {

                    //为了保证不被重复发送通知，或重复执行数据库更新程序，请判断该笔交易状态是否是订单未处理状态
                    if (sOld_trade_status < 1) {

                        orders.setStatus(Constants.ORDERS_STATUS_WAITING_FOR_SHIPMENT);//付款成功，等待买家发货
                        //根据订单号更新订单，把订单状态处理成交易成功
                    }

                } else {
                    orders.setStatus(Constants.ORDERS_STATUS_FAILURE);//订单付款失败
                }


                if (sOld_trade_status < 1) {
                    this.ordersJdbc.update(orders);
                }

            }else {
                logger.info("the order out_trade_no : " + order_no + ", is deleted ================");
            }


            verifyStatus = "success";
        } else {//验证失败
            verifyStatus = "fail";
        }

        logger.info(verifyStatus);
    }
}
